package com.cinemtl.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cinemtl.beans.CartOrder;
import com.cinemtl.beans.ShoppingCart;

/**
 * Servlet implementation class Cart
 */
@WebServlet("/cart")
public class Cart extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Cart() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int idMovie = Integer.valueOf(request.getParameter("id"));
		int quantity = Integer.valueOf(request.getParameter("qty"));
		String action = request.getParameter("action");
		CartOrder order = new CartOrder();
		// UUID idOrder = UUID.randomUUID();
		order.setId(idMovie);
		order.setNbTicket(quantity);

		HttpSession session = request.getSession();

		if (action.equals("addQuantity")) {
			if (ShoppingCart.getOrders().containsKey(idMovie)) {
				ShoppingCart.getOrders().get(idMovie).setNbTicket(0);
				ShoppingCart.getOrders().get(idMovie).incNbTicket(quantity);
			} else {
				ShoppingCart.addOrder(order);
			}
		} else if (action.equals("remove")) {
			ShoppingCart.removeOrder(order.getId());
		}
		else{
			if (ShoppingCart.getOrders().containsKey(idMovie)) {
				ShoppingCart.getOrders().get(idMovie).incNbTicket(quantity);
			} else {
				ShoppingCart.addOrder(order);
			}
		}
		session.setAttribute("cart", ShoppingCart.getOrders());
	}
}
